package com.teradata.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 2018-08-10 13:50 huzy Create 1.0 <br>
 * @project chinabond-edb
 * @description 异步处理配置类
 * @errorcode SystemException</ br>
 * @copyright ©2017-2017 中央结算公司，版权所有。
 */
@Configuration
public class AsyncConfiguration {

    private ThreadPoolTaskExecutor pool;

    private final Map<String, TaskContext> contexts = new ConcurrentHashMap<String, TaskContext>();

    private final TaskExecutor taskExecutor;


    public AsyncConfiguration() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsynchThread-");
        executor.initialize();
        this.pool = executor;
        this.taskExecutor = new TaskExecutor(this.pool);
    }

    public void monitor(TaskContext taskContext) {
        this.taskExecutor.monitor(taskContext);
    }

    public TaskContext taskGroupRegist(String taskGrpName) {
        TaskContext ctx = contexts.get(taskGrpName);
        if (ctx == null) {
            System.out.println("NoGroup regist group " + taskGrpName);
            ctx = new TaskContextImpl(this, taskGrpName);
            contexts.put(taskGrpName, ctx);
        }
        System.out.println("Task Group Name " + taskGrpName);
        return ctx;
    }


    public ThreadPoolTaskExecutor executorService() {
        return this.pool;
    }

    public TaskContext select(String taskGrpName) {
        return (TaskContext) this.contexts.get(taskGrpName);
    }

    public void shutdown() {
        taskExecutor.shutdown();
        pool.shutdown();;
    }

}